package com.skyline.energy.factory;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.skyline.energy.executor.DataAccessExecutor;

/**
 * 数据访问操作的拦截器
 * 
 * @author wuqh
 * @see MethodInterceptor
 */
class DataAccessInterceptor implements MethodInterceptor {
	private static final Logger LOGGER = LoggerFactory.getLogger(DataAccessInterceptor.class);
	private static final int CACHE_INIT_SIZE = 32;

	private final Map<Method, DataAccessExecutor> EXECUTOR_CACHE = new HashMap<Method, DataAccessExecutor>(
			CACHE_INIT_SIZE);

	public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy)
			throws Throwable {
		DataAccessExecutor executor = EXECUTOR_CACHE.get(method);
		if (executor != null) {
			return executor.execute(obj, args);
		} else {
			if (LOGGER.isDebugEnabled()) {
				LOGGER.debug("方法[" + method + "]无对应的DataAccessExecutor实现,采用默认实现执行");
			}
			return getDefaultValue(method.getReturnType());
		}
	}

	public void addDataAccessExecutor(Method method, DataAccessExecutor executor) {
		EXECUTOR_CACHE.put(method, executor);
	}

	/**
	 * 默认返回值
	 * 
	 * @param clazz
	 *            类型
	 * @return Object 返回类型
	 */
	private Object getDefaultValue(Class<?> clazz) {
		if (clazz.isPrimitive()) {
			if (byte.class.equals(clazz)) {
				return (byte) 0;
			} else if (short.class.equals(clazz)) {
				return (short) 0;
			} else if (int.class.equals(clazz)) {
				return 0;
			} else if (long.class.equals(clazz)) {
				return 0L;
			} else if (float.class.equals(clazz)) {
				return 0F;
			} else if (double.class.equals(clazz)) {
				return 0D;
			} else if (char.class.equals(clazz)) {
				return (char) 0;
			} else if (boolean.class.equals(clazz)) {
				return false;
			}
		}

		return null;
	}
}
